import Taro, { useEffect, useState, useRouter, useMemo, useReachBottom }  from '@tarojs/taro'
import { View, Text, Image, Input } from '@tarojs/components'
import { AtModal } from 'taro-ui'
import _get from "lodash/get";

import m from "moment";

// components
import RPlayer from "../../components/rPlayer";

// const
import { OSS_IMAGE_URL_PREFIX, OSS_RECORDING_URL_PREFIX } from '../../constances/constances'

// utils
import getAge from "../../utils/getAge";
import getCurrentDateStr from "../../utils/getCurrentDateStr";
import getLoginInfo from "../../utils/getLoginInfo";
import {get as getGlobal, READ1000_USER_INFO} from "../../globalData";

// api
import api from '../../api/index'

// style
import './index.scss'
import getAvatarImgPrefix from "../../utils/getAvatarImgPrefix";

export default function Recording() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [isMore, setIsMore] = useState(false)
  const PAGE_SIZE = 20

  const [recordingData, setRecordingData] = useState({
    imageKeyTimeArray: [],
    sentenceTimeArray: []
  })

  const [comments, setComments] = useState([])

  const [isOpened, setIsOpened] = useState(false)

  const [likes, setLikes] = useState(0)

  const [isViewerLike, setIsViewerLike] = useState(false)

  const [commentText, setCommentText] = useState('')

  const [userInfo, setUserInfo] = useState({})

  useReachBottom(() => {
    if (isMore) {
      getComments(comments.length, (comments.length + PAGE_SIZE - 1))
    }
  })

  useEffect(async () => {
    const user = getLoginInfo()

    if(!user) {
      return
    }

    setUserInfo(user.user)

    const { orgid, recid, uid } = router.params

    const data = await api.recording.getList({
      uid,
      orgid: orgid || 0,
      recid
    })

    initRecordingData(data)

    getComments();

  }, [router.params])

  // 获取评论
  async function getComments(start = 0, end = PAGE_SIZE - 1, isRefresh = false ) {
    const { recid, uid } = router.params

    const commentData = await api.comment.getCommentList({
      viewerid: uid,
      recid,
      start,
      end
    })

    if(commentData.recording_id) {
      if (commentData.recordingComment) {

        if (isRefresh) {
          setComments(commentData.recordingComment.comments)
        } else {
          setComments([
            ...comments,
            ...commentData.recordingComment.comments
          ])
        }

        if (commentData.recordingComment.comments.length === PAGE_SIZE) {
          setIsMore(true)
        } else {
          setIsMore(false)
        }
      }

      setLikes(commentData.likes)
      setIsViewerLike(commentData.isViewerLike)
    }
  }

  // 数据处理
  function initRecordingData (data) {
    const obj = {}
    obj.nickname = data.nickname  //改成用昵称，用户可以改昵称
    obj.audioShareRecordingData = data.recordingList[0]
    const {
      osskey, book, episode, voice_score,
      pron_accuracy, pron_completion, pron_fluency,
      date_time, json_data, recording_type
    } = obj.audioShareRecordingData

    // 音频地址
    obj.audioUrl = OSS_RECORDING_URL_PREFIX + osskey;

    // 用户音频列表

    // 用户头像
    obj.avatar = OSS_RECORDING_URL_PREFIX + data.avatar_url

    // 用户使用时间
    obj.birthday = data.birthday
    obj.age = getAge(data.birthday, getCurrentDateStr())

    // 书名
    obj.bookName = book

    Taro.setNavigationBarTitle({
      title: book
    })

    // 简介
    obj.episode = episode

    // 得分
    if (voice_score && parseInt(voice_score, 10) > 0) {
      obj.score = voice_score
      if (pron_accuracy != null) {
        // 准确度
        obj.accuracy = Math.round(pron_accuracy).toString();
      }

      if (pron_completion != null) {
        // 完成度
        obj.completion = Math.round(pron_completion * 100).toString();
      }

      if (pron_fluency != null) {
        // 流利度
        obj.fluency = Math.round(pron_fluency * 100).toString();
      }
    }

    // 上传时间
    obj.recordingDate = date_time.substring(0, 10)
    if (data.birthday != null) {
      obj.recordingAge = getAge(data.birthday, obj.recordingDate)
    }

    const { imageKeyTimeArray, sentenceTimeArray } = JSON.parse(json_data)
    // swiper 数据
    obj.imageKeyTimeArray = imageKeyTimeArray.map(img => ({
      ...img,
      imgUrl: OSS_IMAGE_URL_PREFIX + '/' + episode + "/" + book + "/" + img.imageKey
    }))

    // 字幕数据
    obj.sentenceTimeArray = sentenceTimeArray

    // subtitle
    obj.recordingType = recording_type

    setRecordingData(obj)
  }

  // const isComments = useMemo(() => {
  //   return comments.length > 0
  // }, [comments])

  // 关闭对话框
  function handleCancel() {
    setIsOpened(false)
  }

  // 删除
  async function handleDelete() {
    const { commentator_id, time } = isOpened
    const { recid, uid } = router.params
    const token = _get(getGlobal(READ1000_USER_INFO), 'token')
    const data = await api.comment.deleteComment({
      token,
      recording_id: recid,
      user_id: uid,
      commentator_id,
      comment_timeStamp: time,
    })
    if (data.code > 0) {
      Taro.showToast({
        title: '删除成功',
      });

      getComments(0, comments.length, true)
    } else {
      Taro.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
    setIsOpened(false)
  }

  // 点赞
  async function submitPraise() {
    const { recid, uid } = router.params

    if (isViewerLike) {
      return
    }

    const data = await api.comment.submitPraise({
      recording_id: recid,
      viewer_id: uid
    })

    if(data.code > 0) {
      setLikes(likes + 1)
      setIsViewerLike(true)
    }

  }

  // 评论
  async function submitComment() {
    const { uid, recid } = router.params
    const recording_id = recid
    const user_id = uid
    const content = commentText
    const commentator_id = uid
    const commentator_nickname = _get(userInfo, 'nickname')
    const commentator_avatar = getAvatarImgPrefix(_get(userInfo, 'avatar_url'))

    if(!content) {
      return
    }

    if (loading) {
      return
    }

    setLoading(true)

    try{
      const data = await api.comment.summitComment({
        recording_id,
        user_id,
        comment: {
          content,
          commentator_id,
          commentator_nickname,
          commentator_avatar,
          time: new Date(),
        }
      })
      setLoading(false)

      if(data.code > 0) {
        setCommentText('')
        getComments(0, comments.length, true)
      }
    } catch (e) {
      setLoading(false)
    }
  }

  return (
    <View className='recording-page'>
      <RPlayer recordingData={recordingData} />
      {/*书籍信息*/}
      <View className='book-info-container'>
        <View className='book-info-wrapper'>
          <View className='title'>{ recordingData.bookName }</View>
        </View>
      </View>

      {/*用户信息*/}
      <View className='user-info-container'>
        <View className='img-wrapper'>
          <Image src={recordingData.avatar} className='avatar' />
        </View>

        <View className='user-info-wrapper'>
          <View className='nickname'>
            { recordingData.nickname }
        </View>
        <View className='user-age'>年龄：{ recordingData.age }</View>

        <View className='upload-container'>
          <View className='upload-time'>上传：{ recordingData.recordingDate }</View>
        </View>
      </View>

        {
          recordingData.score && (
            <View className='score-info-wrapper'>
              <View className='score'>
                <Text className='num'>{ recordingData.score }</Text>
                <Text>分</Text>
              </View>
              <View className='desc'>综合得分</View>
            </View>
          )
        }
      </View>

      {/*评分详情*/}
      {
        recordingData.score && (
          <View className='score-detail-container'>
            <View className='score-detail-wrapper'>
              <View className='score-detail'>
                <View className='score'><Text className='num'>{ recordingData.accuracy }</Text>分</View>
                发音
              </View>
              <View className='score-detail'>
                <View className='score'><Text className='num'>{ recordingData.completion }</Text>分</View>
                完成度
              </View>
              <View className='score-detail'>
                <View className='score'><Text className='num'>{ recordingData.fluency }</Text>分</View>
                流利度
              </View>
            </View>
          </View>
        )
      }

    {/*  点赞数 */}
      <View className='praise-container'>
        <View
          className={`praise-icon-container ${isViewerLike ? 'active' : ''}`}
          onClick={() => submitPraise()}
        >
          <View className='praise-wrapper'>
            <Image className='icon' src={require('../../assets/praise48X48@2x.png')} />
          </View>
        </View>
        <View className='desc'>
          <Text className='num'>{ likes }</Text> 人点赞
        </View>
      </View>

    {/*  评论管理 */}
    <View className='comment-list-container'>
      <View className='header'>
        <View className='title'>
          作品评论
        </View>
      </View>

      <View className='input-container'>
        <Input
          className='input'
          type='text'
          placeholder='我来说两句'
          value={commentText}
          onInput={(e) => setCommentText(e.detail.value)}
          // onChange={(e) => setCommentText(e.detail.value)}
        />

        <View
          className='comment-btn'
          onClick={() => submitComment()}
        >
          评论
        </View>
      </View>

      <View className='comment-list'>
        {
          comments.map((commentData, index) => (
            <View className='comment-wrapper' key={index}>
              <View className='img-wrapper'>
                <Image className='img' src={commentData.commentator_avatar} />
              </View>

              <View className='comment'>
                <View className='user-wrapper'>
                  <View className='user'>
                    <View className='nickname'>{ commentData.commentator_nickname || commentData.commentator_id }</View>
                    <View className='age'>{ m(commentData.time).format('YYYY-MM-DD  HH:mm:ss') }</View>
                    <Image className='delete' src={require('../../assets/delete.png')} onClick={() => setIsOpened(commentData)} />
                  </View>
                  <View className='content'>{ commentData.content }</View>
                </View>
              </View>
            </View>
          ))
        }
      </View>

      {
        loading && (
          <View className='footer-tips'>
            加载中...
          </View>
        )
      }

      {
        !isMore && (
          <View className='footer-tips'>
            没有更多评论咯~
          </View>
        )
      }
    </View>

      <AtModal
        isOpened={isOpened}
        cancelText='取消'
        confirmText='确认'
        onCancel={handleCancel}
        onConfirm={handleDelete}
        content='确认删除该评论？'
      />
    </View>
  )
}

Recording.config = {
  navigationBarTitleText: '录音详情',
}
